﻿using H2.NET.Web.API.Common;
using H2.NET.Web.API.Model;
using H2.NET.Web.API.Service;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace H2.NET.Web.API
{
    /// <summary>
    /// Summary description for UpdateAccountOwner
    /// </summary>
    public class UpdateAccountOwner : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            HttpResult result = new HttpResult();
            try
            {
                HttpRequest Request = context.Request;
                Stream postData = Request.InputStream;
                StreamReader sRead = new StreamReader(postData, Request.ContentEncoding);
                string postContent = sRead.ReadToEnd();
                sRead.Close();
                Logging.GetLogger().Error(postContent);

                if (postContent != string.Empty && postContent != null)
                {
                    result = HandleData(postContent);
                }
            }
            catch (Exception ex)
            {
                Logging.GetLogger().Error(ex.ToString());
                result.StatusCode = HttpStatusCode.ExpectationFailed;
                result.StatusDescription = ex.ToString();
            }
        }

        private HttpResult HandleData(string postContent)
        {
            HttpResult result = new HttpResult();

            List<AccountOwnerModel> accountList = new List<AccountOwnerModel>();
            accountList = JsonHelper.DeserializeJsonToList<AccountOwnerModel>(postContent);


            if (DBService.SaveAccountOwner(accountList))
            {
                result.StatusCode = HttpStatusCode.OK;
                result.StatusDescription = "数据保存成功。";
                result.Html = "<h1>数据保存成功</h1>";
            }
            else
            {
                result.StatusCode = HttpStatusCode.ExpectationFailed;
                result.StatusDescription = "数据保存失败。";
                result.Html = "<h1>数据保存失败</h1>";
            }

            return result;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}